'use strict';
const ora = require('ora');
const cp = require('child_process');

function isObject(o) {
  return Object.prototype.toString.call(o) === '[object Object]';
}

/** 开启终端loading */
function spinnerStart(options) {
  let spinner = ora({ spinner: 'dots', ...options });
  spinner.start();
  return spinner;
}

/** 是当前进程延后一秒执行 */
function sleep(time = 1000) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

/**
 * 执行一条命令
 * 改造spawn兼容windows，macOs
 */
function exec(command, args, options) {
  const win32 = process.platform === 'win32';

  const cmd = win32 ? 'cmd' : command;
  const cmdArgs = win32 ? ['/c'].concat(command, args) : args;

  return cp.spawn(cmd, cmdArgs, options || {});
}

function execAsync(command, args, options) {
  return new Promise((resolve, reject) => {
    const p = exec(command, args, options);
    p.on('error', (error) => {
      reject(error);
    });
    p.on('exit', (code) => {
      resolve(code);
    });
  });
}

module.exports = { isObject, spinnerStart, sleep, exec, execAsync };
